package com.yc.vcode.web;

import com.yc.vcode.VcodeException;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class VcodeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler) throws Exception {
       //用户输入的验证码
        String rcode=request.getParameter("rcode");
        //会话保存的验证码
        String vcode= (String) request.getSession().getAttribute("vcode");
        System.out.println("vcode = " + vcode);
        Long time= (Long) request.getSession().getAttribute("timeOut");
        if(time<System.currentTimeMillis()){
            throw new VcodeException("验证码过期");
        }
        if(vcode==null){
            throw new VcodeException("请先获取验证码");
        }
        if(rcode==null){
            throw new VcodeException("请输入验证码");
        }
        if(!rcode.equalsIgnoreCase(vcode)){
            throw new VcodeException("输入的验证码错误");
        }
        request.getSession().removeAttribute("vcode");
        request.getSession().removeAttribute("timeOut");
        return true;
    }
}
